package com.watson.nettydemo.demo09;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

import static io.netty.handler.timeout.IdleState.READER_IDLE;

/**
 * SimpleChannelInboundHandler 与 ChannelInboundHandlerAdapter 的区别，，SimpleChannelInboundHandler会将消息自动释放
 *
 * @author: llun
 * @date: 2022/3/11 14:54
 * @version: 1.0
 */
public class IdeSocketServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
        System.out.println();
    }

    /**
     * 用户捕捉server的各种事件
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent stateEvent = (IdleStateEvent) evt;

            if (stateEvent.state().equals(READER_IDLE)) {
                System.out.println("将要关闭");
                // 关闭连接if
                ctx.close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
